package com.zhangxiaofanfan.arthas.service.impl;

import com.zhangxiaofanfan.arthas.db.DataCache;
import com.zhangxiaofanfan.arthas.pojo.ArthasPO;
import com.zhangxiaofanfan.arthas.service.ArthasService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 学习 Arthas 使用的服务器类实现
 *
 * @author zhangxiaofanfan
 * @date 2025-03-11 10:04:40
 */
@Slf4j
@Service
public class ArthasServiceImpl implements ArthasService {
    @Autowired
    private DataCache cache;
    @Autowired
    private ThreadPoolTaskExecutor executor;

    private AtomicInteger cnt = new AtomicInteger(0);
    private static final String PREFIX = "zhangxiaofanfan";

    @Override
    @Async("zxffTaskExecutor")
    public void insertTaskVoid(int taskId) {
        insertTaskMethod(taskId);
    }

    @Override
    @Async("zxffTaskExecutor")
    public CompletableFuture<Integer> insertTask(int taskId) {
        insertTaskMethod(taskId);
        return CompletableFuture.completedFuture(1);
    }

    public void insertTaskMethod(int taskId) {
        log.info("开始连接数据库, 等待完成链接......");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("链接数据库成功, 请求数据......");
        ArthasPO arthas = cache.getArthasCondition(taskId);
        log.info("任务id[{}]查询到的任务信息为: {}", taskId, arthas.getName());
        cache.insertArthasTask(taskId, ArthasPO.builder().id(taskId).name(String.format("%s-%d", PREFIX, cnt.addAndGet(1))).build());
    }
}
